package com.co.recommend.listener;


import com.alibaba.otter.canal.protocol.CanalEntry;
import com.co.recommend.dao.SubMapper;
import com.co.recommend.service.SubService;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 推送监听
 */
@CanalEventListener

public class pubListener {

    private static final Logger log = LoggerFactory.getLogger(pubListener.class);

    @Autowired
    private SubService subService;

    @Autowired
    private SubMapper subMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ListenPoint(schema = "co_cornpub", table = {"tv_vdetail"}, eventType = CanalEntry.EventType.UPDATE)
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //修改前数据，并转换为map
        Map oldMap = new HashMap<>();
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            oldMap.put(column.getName(), column.getValue());
        }

        //修改后数据
        Map newMap = new HashMap<>();
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            newMap.put(column.getName(), column.getValue());
        }
        System.err.println("tv_vdetail表数据的行发生变化: " + oldMap.get("status") + "---->" + newMap.get("status"));
        //审核状态0----》1
        if ("0".equals(oldMap.get("status")) && "1".equals(newMap.get("status"))) {
            String upName = (String) newMap.get("username");

            List<String> subs = subMapper.findSubName(upName);
            if (subs == null || subs.size() <= 0) {
                //还没有人订阅
                log.info("没有人订阅你，不用推送");
                return;
            }
            String aid = (String) newMap.get("aid");

            Map<String, String> map = new HashMap<>();
            map.put("upName", upName);
            map.put("aid", aid);
            rabbitTemplate.convertAndSend("pubVideo", "", map);

            subService.push(upName, aid);
        }

    }
}
